package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import common.Yaml;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.configuration.ConfigurationException;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;

import static com.alibaba.fastjson.JSON.*;

public class YamlReadUtil {
    public static final String system = "env.properties";
    private static Object HashMap;

    /**
     * @param path      对象库文件地址
     * @param className className 页面名字
     * @return 返回Yaml 对象
     */
    public static Yaml getLocatorMap(String path, String className) throws FileNotFoundException, YamlException {
        FileReader fileReader = new FileReader(path);
        YamlReader yamlReader = new YamlReader(fileReader);
        Object yamlObject = yamlReader.read();
        HashMap yamlMap = (HashMap) yamlObject;
        ArrayList<HashMap<String, Object>> pages = (ArrayList<HashMap<String, Object>>) yamlMap.get("classes");
        Yaml yaml = null;
//        Yaml yaml = new Yaml();
        for (HashMap<String, Object> pageNode : pages) {
            HashMap<String, Object> pageElement = (HashMap<String, Object>) pageNode.get("class");
            if (pageElement.get("className").toString().equalsIgnoreCase(className))//判断是否需要获取的class节点
            {

                  String jsonString=JSONObject.toJSONString(pageElement);
                JSONObject jb= JSONObject.parseObject(jsonString);
                yaml= JSON.toJavaObject(jb,Yaml.class);

                //用commons-beanutils
//                BeanUtils.populate(yaml, pageElement);

            }
        }

        return yaml;
    }


    public static void main(String[] args) throws FileNotFoundException, YamlException {
        String path = "src/main/resources/QualityMonitor.yml";
        Yaml yaml = YamlReadUtil.getLocatorMap(path, "business.cdss.LaunchQc");
        JSONObject a =(JSONObject)  yaml.getDatas().get(0).get("whereResult");
        String c = a.toJSONString();
        System.out.println(c);
    }


}
